<template>
	<view class="page">
		<topVue :title="$t('充值')" :right="$t('充值明细')" @rightClick="$tools.route('./chargeRecord')"></topVue>
		<view class="inpVue margin30 padding30">
			<text style="font-size: 32rpx; color: #333333;">{{ $t('充值数量') }}</text>
			<u-gap height="30"></u-gap>
			<input type="text" :placeholder="$t('请输入充值数量')" @change="quantityChange" v-model="quantity"
				placeholder-style="color: #CCC; font-size: 30rpx;" />
		</view>
		<view class="btn margin80" @click="recharge">{{ $t('提交') }}</view>
	</view>
</template>

<script>
	import {
		ethers
	} from "ethers";
	import wallet from "../../common/wallet";
	import walletConfig from "../../common/wallet-config";

	export default {
		data() {
			return {
				quantity: "",
				allowance: "",
				address: ""
			}
		},
		async onLoad() {
			this.address = uni.getStorageSync("localeAddress");
			await this.getAllowance();
		},
		methods: {
			async getAllowance() {
				await wallet.getTokenAllowance(walletConfig.usdtAddress, this.address, walletConfig.factoryAddress)
					.then(res => {
						this.allowance = res;
					})
			},
			// 充值
			async recharge() {
				if (Number(this.allowance) < Number(this.quantity)) {
					await this.approve().then(async () => {
						await wallet.recharge(ethers.parseEther(this.quantity))
							.then(async res => {
								this.$u.toast("充值成功");
								await this.getAllowance();
							}).catch(err => {
								this.$u.toast(err.message)
							})
					}).catch(err => {
						this.$u.toast(err.message)
					})
				} else {
					await wallet.recharge(ethers.parseEther(this.quantity))
						.then(res => {
							this.$u.toast(this.$t("成功"))
							this.getAllowance();
						}).catch(err => {
							this.$u.toast(err.message)
						})
				}
			},
			async approve() {
				await wallet.approve(walletConfig.usdtAddress, walletConfig.factoryAddress, ethers.parseEther(this
					.quantity)).then(res => {
					this.$u.toast(this.$t("成功"))
					this.getAllowance();
				})
			}
		}
	}
</script>

<style lang="less" scoped>
	.inpVue {
		width: 690rpx;
		background: rgba(237, 244, 255, 0.8);
		border-radius: 20rpx;

		input {
			width: 100%;
			height: 70rpx;
			font-size: 30rpx;
			color: #333;
		}
	}

	.btn {
		width: 690rpx;
		height: 80rpx;
		background: #4D9FED;
		border-radius: 40rpx;
		line-height: 80rpx;
		text-align: center;
		color: #fff;
		font-size: 30rpx;
	}
</style>